/**
 * date：2010-11-15
 * author：eason
 * description：缓存系统管理器.
 * 该类实现单例模式.
 * 该类可以将需要执行的动作缓存起来(cache方法).通过release进行释放.
 * 该类还提供一组锁定与解锁的静态方法.该组方法仅用于标记目的,不参与缓存的动作的相关操作.
 */
package com.pickgliss.manager
{
	import com.pickgliss.action.IAction;
	import com.pickgliss.action.TickOrderQueueAction;
	
	import flash.utils.Dictionary;
	
	public class CacheSysManager
	{
		private static var instance : CacheSysManager;
		
		private var _cacheDic : Dictionary;
		private static var _lockDic : Dictionary = new Dictionary();
		
		public function CacheSysManager()
		{
			_cacheDic = new Dictionary();
			_lockDic = new Dictionary();
		}
		public static function getInstance():CacheSysManager
		{
			if(instance == null){
				instance = new CacheSysManager();
			}
			return instance;
		}
		
		
		/**
		 * 通过标记字符串缓存指定的动作 
		 * @param flag 标记字符串
		 * @param action 要缓存的动作.
		 * 
		 */		
		public function cache(flag : String, action : IAction):void
		{
			if(!_cacheDic[flag]){
				_cacheDic[flag] = new Array();
			}
			_cacheDic[flag].push(action);
		}
		/**
		 * 释放指定标记的被缓存起来的动作序列. 
		 * @param flag
		 * @param delay 指定的延迟执行的毫秒数.
		 * 
		 */		
		public function release(flag : String, delay : uint = 0):void
		{
			var action : IAction;
			if(_cacheDic[flag]){
				action = getReleaseAction(_cacheDic[flag] as Array, delay);
				action.act();
				
				delete _cacheDic[flag];
			}
		}
		
		/**
		 *单个执行压入的函数 
		 * 
		 */		
		public function singleRelease(flag : String):void
		{
			var action :IAction;
			var actQueue:Array;
			if(_cacheDic[flag])
			{
				actQueue = _cacheDic[flag];
				if(actQueue[0])(actQueue[0] as IAction).act();
				actQueue.shift();
			}
		}
		
		/**
		 *压入函数 
		 */		
		public function cacheFunction(flag : String , action : IAction):void
		{
			if(!_cacheDic[flag]){
				_cacheDic[flag] = new Array();
			}
			_cacheDic[flag].push(action);
		}
		
			
		/**
		 * 获得释放所缓存的动作的动作.
		 * @param actions
		 * @return 
		 * 
		 */	
		private static function getReleaseAction(actions : Array, delay : uint = 0):IAction
		{
			var action : IAction = new TickOrderQueueAction(actions, 100, delay);
			return action;
		}
		
		/**
		 * 锁定缓存标记.
		 * 该方法仅仅是标记某个字符串被锁定了.
		 * 这里的设置将反映在isLock(flag : String):Boolean方法中.
		 * @param flag
		 * 
		 */		
		public static function lock(flag : String):void
		{
			_lockDic[flag] = true;
		}
		/**
		 * 对指定的缓存标记进行解锁.
		 * 这里的设置将反映在isLock(flag : String):Boolean方法中.
		 * 如果要执行缓存的动作,还需执行release方法.
		 * @param flag
		 * 
		 */	
		public static function unlock(flag : String):void
		{
			delete _lockDic[flag];
		}
		
		public static function isLock(flag : String):Boolean
		{
			return _lockDic[flag]?true:false;
		}
		
	}
}